<template>
	<view class="page friend-requests-page">
		<!-- 自定义导航栏 -->
		<br>
		<ob-navbar title="好友申请" :show-back="true" />
		<br>
		
		<view class="content">
			<!-- 筛选选项卡 -->
			<view class="tabs-section">
				<view class="tabs-container">
					<view 
						v-for="(tab, index) in tabs" 
						:key="index"
						class="tab-item" 
						:class="{ active: currentTab === tab.value }"
						@click="switchTab(tab.value)"
					>
						<text class="tab-text">{{ tab.label }}</text>
						<view v-if="tab.count > 0" class="tab-badge">{{ tab.count }}</view>
					</view>
				</view>
			</view>
			
			<!-- 批量操作栏 -->
			<view v-if="selectedRequests.length > 0" class="batch-actions">
				<text class="selected-count">已选择 {{ selectedRequests.length }} 项</text>
				<view class="action-buttons">
					<button class="batch-btn accept" @click="batchAccept">批量同意</button>
					<button class="batch-btn reject" @click="batchReject">批量拒绝</button>
				</view>
			</view>
			
			<!-- 好友申请列表 -->
			<view class="requests-section">
				<view class="requests-list">
					<view 
						v-for="request in filteredRequests" 
						:key="request.id"
						class="request-item"
						:class="{ 'processed': request.status !== 'pending' }"
					>
						<view 
							v-if="request.type === 'received' && request.status === 'pending'" 
							class="select-checkbox" 
							@click.stop="toggleSelect(request)"
						>
							<text class="checkbox-icon">{{ request.selected ? '✓' : '' }}</text>
						</view>
						
						<image 
							:src="request.fromUser.avatar || 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'"
							class="user-avatar" 
							mode="aspectFill"
							@click="viewUserProfile(request.fromUser)"
						/>
						
						<view class="request-content">
							<view class="request-header">
								<text class="user-name">{{ request.fromUser.nickname || request.fromUser.realName || request.fromUser.username }}</text>
								<text class="request-time">{{ formatTime(request.createTime) }}</text>
							</view>
							<text class="request-message">{{ request.message || '申请添加您为好友' }}</text>
							<view v-if="request.verifyMessage" class="request-source">
								<text class="source-text">{{ request.verifyMessage }}</text>
							</view>
						</view>
						
						<view class="request-actions">
							<!-- 只有收到的申请且状态为待处理时才显示操作按钮 -->
							<view v-if="request.type === 'received' && request.status === 'pending'">
								<button class="action-btn reject-btn" @click="handleRequest(request, 'reject')">拒绝</button>
								<button class="action-btn accept-btn" @click="handleRequest(request, 'accept')">同意</button>
							</view>
							<!-- 其他情况显示状态 -->
							<view v-else class="status-badge" :class="request.status">
								<text class="status-text">{{ getStatusText(request.status, request.type) }}</text>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 空状态 -->
				<view v-if="filteredRequests.length === 0" class="empty-state">
					<ob-empty 
						:image="'/static/images/empty-requests.png'"
						:title="getEmptyTitle()"
						:description="getEmptyDescription()"
					/>
				</view>
			</view>
		</view>
		
		<!-- 处理确认弹窗 -->
		<view v-if="showConfirmModal" class="confirm-modal" @click="showConfirmModal = false">
			<view class="confirm-content" @click.stop>
				<view class="confirm-header">
					<text class="confirm-title">{{ confirmAction === 'accept' ? '同意好友申请' : '拒绝好友申请' }}</text>
				</view>
				<view class="confirm-body">
					<text class="confirm-text">
						确定要{{ confirmAction === 'accept' ? '同意' : '拒绝' }}来自 {{ selectedRequest?.fromUser?.nickname || '用户' }} 的好友申请吗？
					</text>
				</view>
				<view class="confirm-actions">
					<button class="cancel-btn" @click="showConfirmModal = false">取消</button>
					<button class="confirm-btn" @click="confirmHandleRequest">确定</button>
				</view>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" text="加载中..." />
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import friendApi from '../../api/friend.js'
import { formatDistanceToNow } from '../../utils/common.js'

// 响应式数据
const requests = ref([])
const currentTab = ref('received')
const isLoading = ref(false)
const showConfirmModal = ref(false)
const selectedRequest = ref(null)
const confirmAction = ref('')

// 选项卡配置
const tabs = ref([
	{ label: '收到的', value: 'received', count: 0 },
	{ label: '发出的', value: 'sent', count: 0 },
	{ label: '已处理', value: 'processed', count: 0 }
])

// 计算属性
const filteredRequests = computed(() => {
	let filtered = []
	
	switch (currentTab.value) {
		case 'received':
			filtered = requests.value.filter(req => req.type === 'received' && req.status === 'pending')
			break
		case 'sent':
			filtered = requests.value.filter(req => req.type === 'sent')
			break
		case 'processed':
			filtered = requests.value.filter(req => req.type === 'received' && req.status !== 'pending')
			break
		default:
			filtered = requests.value
	}
	
	return filtered
})

const selectedRequests = computed(() => {
	return requests.value.filter(request => request.selected && request.type === 'received' && request.status === 'pending')
})

// 生命周期
onMounted(() => {
	loadRequests()
})

// 方法
const loadRequests = async () => {
	try {
		isLoading.value = true
		
		// 并行获取收到的和发出的申请
		const [receivedResponse, sentResponse] = await Promise.all([
			friendApi.getFriendRequests({ type: 'received' }),
			friendApi.getFriendRequests({ type: 'sent' })
		])
		
		console.log('后端返回数据:', { receivedResponse, sentResponse })
		
		// 处理后端返回的数据格式
		const processRequestData = async (dataArray, type) => {
			// 确保dataArray是数组
			const actualData = Array.isArray(dataArray) ? dataArray : (dataArray?.data || [])
			if (!Array.isArray(actualData)) return []

			const processedData = []
			
			for (const userFriend of actualData) {
				// 根据friendStatus判断状态：1-待通过, 2-已通过, 3-被拒绝
				let status = 'pending'
				if (userFriend.friendStatus === 2) status = 'accepted'
				else if (userFriend.friendStatus === 3) status = 'rejected'
				
				// 使用后端返回的真实用户信息
				const friendUser = userFriend.friendUserInfo
				const fromUser = {
					id: friendUser?.id || 0,
					nickname: friendUser?.nickname || '未知用户',
					username: friendUser?.username || '',
					realName: friendUser?.realName || '',
					email: friendUser?.email || '',
					phone: friendUser?.phone || '',
					avatar: friendUser?.avatar || 'https://img.88icon.com/download/jpg/20200901/3e9ce3813b7199ea9588eeb920f41208_512_512.jpg!bg'
				}
				
				processedData.push({
					id: userFriend.friendId,
					friendId: userFriend.friendId,
					userId: userFriend.userId,
					friendUserId: userFriend.friendUserId,
					friendStatus: userFriend.friendStatus,
					status: status,
					createTime: userFriend.createTime,
					updateTime: userFriend.updateTime,
					message: '申请添加您为好友',
					verifyMessage: userFriend.verifyMessage || '',
					source: 'search',
					fromUser: fromUser,
					type: type,
					selected: false
				})
			}
			
			return processedData
		}
		
		const receivedRequests = await processRequestData(receivedResponse, 'received')
		const sentRequests = await processRequestData(sentResponse, 'sent')
		
		requests.value = [...receivedRequests, ...sentRequests]
		
		console.log('处理后的数据:', requests.value)
		
		// 更新计数
		updateTabCounts()
		
	} catch (error) {
		console.error('加载好友申请失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

const updateTabCounts = () => {
	tabs.value[0].count = requests.value.filter(req => req.type === 'received' && req.status === 'pending').length
	tabs.value[1].count = requests.value.filter(req => req.type === 'sent').length
	tabs.value[2].count = requests.value.filter(req => req.type === 'received' && req.status !== 'pending').length
}

const switchTab = (tabValue) => {
	currentTab.value = tabValue
	// 清除所有选择
	requests.value.forEach(request => {
		request.selected = false
	})
}

const formatTime = (timestamp) => {
	if (!timestamp) return ''
	return formatDistanceToNow(timestamp)
}

const getSourceText = (source) => {
	const sourceMap = {
		search: '搜索添加',
		scan: '扫码添加',
		nearby: '附近的人',
		contacts: '通讯录',
		group: '群聊',
		default: '其他'
	}
	return sourceMap[source] || sourceMap.default
}

const getStatusText = (status, type) => {
	if (type === 'sent') {
		// 发出的申请状态
		const statusMap = {
			pending: '等待对方同意',
			accepted: '已同意',
			rejected: '已拒绝'
		}
		return statusMap[status] || status
	} else {
		// 收到的申请状态
		const statusMap = {
			pending: '待处理',
			accepted: '已同意',
			rejected: '已拒绝',
			expired: '已过期'
		}
		return statusMap[status] || status
	}
}

const getEmptyTitle = () => {
	const titleMap = {
		received: '暂无新的好友申请',
		sent: '暂无发出的申请',
		processed: '暂无已处理的申请'
	}
	return titleMap[currentTab.value] || '暂无申请'
}

const getEmptyDescription = () => {
	const descMap = {
		received: '当有人向您发送好友申请时会显示在这里',
		sent: '您发送的好友申请会显示在这里',
		processed: '已处理的好友申请会显示在这里'
	}
	return descMap[currentTab.value] || ''
}

const toggleSelect = (request) => {
	request.selected = !request.selected
}

const viewUserProfile = (user) => {
	uni.navigateTo({
		url: `/pages/profile/user?userId=${user.id}`
	})
}

const handleRequest = (request, action) => {
	selectedRequest.value = request
	confirmAction.value = action
	showConfirmModal.value = true
}

const confirmHandleRequest = async () => {
	try {
		// 使用friendId作为请求ID
		await friendApi.handleFriendRequest(selectedRequest.value.friendId, confirmAction.value)
		
		// 更新本地状态
		selectedRequest.value.status = confirmAction.value === 'accept' ? 'accepted' : 'rejected'
		selectedRequest.value.selected = false
		
		// 更新计数
		updateTabCounts()
		
		showConfirmModal.value = false
		
		uni.showToast({
			title: confirmAction.value === 'accept' ? '已同意申请' : '已拒绝申请',
			icon: 'success'
		})
	} catch (error) {
		console.error('处理好友申请失败:', error)
		uni.showToast({
			title: '操作失败',
			icon: 'none'
		})
	}
}

const batchAccept = () => {
	if (selectedRequests.value.length === 0) return
	
	uni.showModal({
		title: '批量同意',
		content: `确定要同意选中的${selectedRequests.value.length}个好友申请吗？`,
		success: async (res) => {
			if (res.confirm) {
				try {
					// 使用friendId作为请求ID
					await friendApi.batchHandleFriendRequests(selectedRequests.value.map(r => r.friendId), 'accept')
					
					// 更新状态
					selectedRequests.value.forEach(request => {
						request.status = 'accepted'
						request.selected = false
					})
					
					updateTabCounts()
					
					uni.showToast({
						title: '批量操作成功',
						icon: 'success'
					})
				} catch (error) {
					console.error('批量同意失败:', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				}
			}
		}
	})
}

const batchReject = () => {
	if (selectedRequests.value.length === 0) return
	
	uni.showModal({
		title: '批量拒绝',
		content: `确定要拒绝选中的${selectedRequests.value.length}个好友申请吗？`,
		confirmColor: '#ff4757',
		success: async (res) => {
			if (res.confirm) {
				try {
					// 使用friendId作为请求ID
					await friendApi.batchHandleFriendRequests(selectedRequests.value.map(r => r.friendId), 'reject')
					
					// 更新状态
					selectedRequests.value.forEach(request => {
						request.status = 'rejected'
						request.selected = false
					})
					
					updateTabCounts()
					
					uni.showToast({
						title: '批量操作成功',
						icon: 'success'
					})
				} catch (error) {
					console.error('批量拒绝失败:', error)
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					})
				}
			}
		}
	})
}
</script>

<style lang="scss" scoped>
.friend-requests-page {
	background: #FAFAFA;
	min-height: 100vh;
}

.content {
	padding: 0;
}

.tabs-section {
	background: #FFFFFF;
	margin: 15px;
	border-radius: 8px;
	overflow: hidden;
}

.tabs-container {
	display: flex;
	padding: 0 10px;
}

.tab-item {
	flex: 1;
	text-align: center;
	padding: 15px 0;
	position: relative;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 4px;
	
	&.active {
		.tab-text {
			color: #495057;
			font-weight: 600;
		}
		
		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
			width: 30px;
			height: 2px;
			background: #495057;
		}
	}
}

.tab-text {
	font-size: 14px;
	color: #999999;
}

.tab-badge {
	background: #DC3545;
	color: #FFFFFF;
	font-size: 10px;
	padding: 2px 5px;
	border-radius: 8px;
	min-width: 16px;
	text-align: center;
}

.batch-actions {
	background: #FFFFFF;
	margin: 0 15px 15px;
	border-radius: 8px;
	padding: 15px 20px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	border-left: 3px solid #495057;
}

.selected-count {
	font-size: 14px;
	color: #333333;
	font-weight: 500;
}

.action-buttons {
	display: flex;
	gap: 10px;
}

.batch-btn {
	height: 32px;
	border: none;
	border-radius: 4px;
	padding: 0 16px;
	font-size: 12px;
	
	&.accept {
		background: #495057;
		color: #FFFFFF;
	}
	
	&.reject {
		background: #F8F9FA;
		color: #6C757D;
		border: 1px solid #E9ECEF;
	}
}

.requests-section {
	background: #FFFFFF;
	margin: 0 15px;
	border-radius: 8px;
	overflow: hidden;
}

.requests-list {
	padding: 0 20px;
}

.request-item {
	display: flex;
	align-items: flex-start;
	padding: 15px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
	
	&.processed {
		opacity: 0.7;
	}
}

.select-checkbox {
	width: 18px;
	height: 18px;
	border: 1px solid #CED4DA;
	border-radius: 3px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 12px;
	margin-top: 16px;
	background: #FFFFFF;
}

.checkbox-icon {
	font-size: 10px;
	color: #495057;
}

.user-avatar {
	width: 50px;
	height: 50px;
	border-radius: 25px;
	margin-right: 12px;
	margin-top: 2px;
}

.request-content {
	flex: 1;
	min-width: 0;
}

.request-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 6px;
}

.user-name {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
	flex: 1;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.request-time {
	font-size: 12px;
	color: #999999;
	flex-shrink: 0;
}

.request-message {
	font-size: 13px;
	color: #666666;
	line-height: 1.4;
	margin-bottom: 6px;
}

.request-source {
	margin-top: 4px;
}

.source-text {
	font-size: 12px;
	color: #999999;
}

.request-actions {
	margin-left: 12px;
	margin-top: 2px;
}

.action-btn {
	height: 32px;
	border: none;
	border-radius: 4px;
	padding: 0 16px;
	font-size: 12px;
	margin-left: 8px;
	
	&.accept-btn {
		background: #495057;
		color: #FFFFFF;
	}
	
	&.reject-btn {
		background: #F8F9FA;
		color: #6C757D;
		border: 1px solid #E9ECEF;
	}
}

.status-badge {
	padding: 6px 12px;
	border-radius: 12px;
	font-size: 12px;
	
	&.accepted {
		background: #E8F5E8;
		color: #388E3C;
	}
	
	&.rejected {
		background: #FFEBEE;
		color: #D32F2F;
	}
	
	&.expired {
		background: #F5F5F5;
		color: #757575;
	}
}

.status-text {
	font-size: 12px;
}

.empty-state {
	padding: 50px 20px;
	text-align: center;
}

.confirm-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
}

.confirm-content {
	background: #FFFFFF;
	border-radius: 12px;
	margin: 0 40px;
	max-width: 320px;
	width: 100%;
}

.confirm-header {
	padding: 20px 20px 10px;
	border-bottom: 1px solid #F0F0F0;
}

.confirm-title {
	font-size: 18px;
	font-weight: 600;
	color: #333333;
	text-align: center;
}

.confirm-body {
	padding: 20px;
}

.confirm-text {
	font-size: 14px;
	color: #666666;
	line-height: 1.5;
	text-align: center;
}

.confirm-actions {
	display: flex;
	border-top: 1px solid #F0F0F0;
}

.cancel-btn,
.confirm-btn {
	flex: 1;
	height: 50px;
	border: none;
	font-size: 16px;
	background: transparent;
	
	&.cancel-btn {
		color: #999999;
		border-right: 1px solid #F0F0F0;
	}
	
	&.confirm-btn {
		color: #495057;
		font-weight: 500;
	}
}
</style>